package com.silence.gankio.widget

import android.content.Context
import android.content.res.Resources
import android.os.Build
import android.support.v4.content.ContextCompat
import android.util.AttributeSet
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewTreeObserver
import android.widget.TextView
import com.google.android.flexbox.*
import com.silence.gankio.R
import java.util.*

class LabelView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FlexboxLayout(context, attrs, defStyleAttr), ViewTreeObserver.OnGlobalLayoutListener {

    private val labelTexts = ArrayList<String>()
    private var itemMargin: Int = 0
    private var mWidth: Int = 0
    private var onLabelViewListener: OnLabelViewListener? = null
    private var paddingVertical = 0
    private var paddingHorizontal = 0

    private var labels: MutableList<String>? = null

    init {
        alignContent = AlignContent.FLEX_START
        alignItems = AlignItems.CENTER
        flexDirection = FlexDirection.ROW
        flexWrap = FlexWrap.WRAP
        justifyContent = JustifyContent.FLEX_START
        itemMargin = dp2px(4f)
        paddingVertical = dp2px(3f)
        paddingHorizontal = dp2px(6f)
        viewTreeObserver.addOnGlobalLayoutListener(this)
        removeAllViews()
    }

    private var newHeight = 0

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
//        setMeasuredDimension(measuredWidth, newHeight)//设置宽高
    }


    fun getLabels(): List<String>? {
        return labels
    }

    fun setLabels(l: MutableList<String>): LabelView {
        labels = l

        removeAllViews()
        labels?.let {
            if (it.isNotEmpty()) {

                newHeight = 0
                for (i in it.indices) {
                    val item = LayoutInflater.from(context)
                        .inflate(com.kongzue.stacklabelview.R.layout.layout_label, null, false)

                    newHeight = item.measuredHeight

                    addView(item)
                }
            }
        }
        return this
    }

    private fun dp2px(dpValue: Float): Int {
        return (0.5f + dpValue * Resources.getSystem().displayMetrics.density).toInt()
    }

    private fun px2dp(pxValue: Int): Float {
        return pxValue / Resources.getSystem().displayMetrics.density
    }

    override fun onGlobalLayout() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            viewTreeObserver.removeOnGlobalLayoutListener(this)
        } else {
            viewTreeObserver.removeGlobalOnLayoutListener(this)
        }

        mWidth = (measuredWidth - paddingLeft - paddingRight) / 4 - itemMargin * 2
//        mWidth = (measuredWidth - paddingLeft - paddingRight)

        val labelView = createLabelView("添加标签")
        labelView.setOnClickListener { view ->
            onLabelViewListener?.onAddLabelClicked(view)
        }
        initLabelView(labelView)
    }

    fun setOnAddClickListener(listener: OnLabelViewListener) {
        this.onLabelViewListener = listener
    }

    fun setNewLabel(contents: MutableList<String>) {
        removeAllViews()
        for (content in contents) {
            addLabel(content)
        }
    }

    fun addLabel(contents: MutableList<String>) {
        for (content in contents) {
            addLabel(content)
        }
    }

    fun addLabel(content: String) {
        val labelView = createLabelView(content)
        initLabelView(labelView)
    }

    private fun createLabelView(content: String): TextView {
        val textView = TextView(context)
        with(textView) {
            text = content
            gravity = Gravity.CENTER
            textSize = 10F
            setTextColor(ContextCompat.getColor(context, android.R.color.black))
            setBackgroundResource(R.drawable.bg_default_button)
            setOnClickListener {
                onLabelViewListener?.onLabelClicked(it, this@LabelView.indexOfChild(this), text.toString())
            }
            setPadding(paddingHorizontal, paddingVertical, paddingHorizontal, paddingVertical)
        }
        return textView
    }

    private fun initLabelView(view: View) {
        addView(view, 0)
        val layoutParams = view.layoutParams as FlexboxLayout.LayoutParams
        layoutParams.width = mWidth
//        layoutParams.height = mWidth
        layoutParams.setMargins(itemMargin, itemMargin, itemMargin, itemMargin)
    }

    public interface OnLabelViewListener {
        fun onAddLabelClicked(view: View)
        fun onLabelClicked(view: View, index: Int, content: String)
    }

}